package com.mission.schedule.receiver;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.mission.schedule.activity.MainActivity;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.SuccessOrFailBean;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.SharedPrefUtil;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import java.util.Date;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";
    SharedPrefUtil sp = null;
    String userid = "";

    @Override
    public void onReceive(final Context context, Intent intent) {
        sp = new SharedPrefUtil(context, ShareFile.USERFILE);
        userid = sp.getString(context, ShareFile.USERFILE, ShareFile.USERID, "");

        synchronized (context) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (DateUtil.formatDate(new Date()).equals(
                            sp.getString(context, ShareFile.USERFILE, ShareFile.LOGINTIME, DateUtil.formatDate(new Date())))) {
                        updateLoginDate(context);
                    } else {
                        if (!DateUtil.formatDate(new Date()).equals(
                                sp.getString(context, ShareFile.USERFILE, ShareFile.LOGINTIME2, DateUtil.formatDate(new Date())))) {
                            sp.putString(context, ShareFile.USERFILE, ShareFile.LOGINTIME2, DateUtil.formatDate(new Date()));
                            updateLoginDate(context);
                        }
                    }
                }
            }, 2000);
        }
        String path = URLConstants.新游客试用 + "?phoneType=" + android.os.Build.MODEL.replace(" ", "")
                + "&id=" + userid + "&version=" + getVersion(context) + "&pushMac=" + JPushInterface.getRegistrationID(context);

        Bundle bundle = intent.getExtras();
//		Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
//		Bundle extras = new Bundle();
//		intentappwidget.putExtras(extras);
//		context.sendBroadcast(intentappwidget);
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            //send the Registration Id to your server...
            String pushAlias = sp.getString(context, ShareFile.USERFILE, ShareFile.PUSH_ALIAS, "0");// 第一次
            if ("0".equals(pushAlias)) {
                // 调用JPush API设置Alias
                String udid = JPushInterface.getRegistrationID(context);
                JPushInterface.setAliasAndTags(context, udid, null, null);
                sp.putString(context, ShareFile.USERFILE, ShareFile.PUSH_ALIAS, "1");
            }

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.e(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
//        	processCustomMessage(context, bundle);

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.e(TAG, "[MyReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Log.e(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.e(TAG, "[MyReceiver] 用户点击打开了通知");

            //打开自定义的Activity
            Intent i = new Intent(context, MainActivity.class);
            i.putExtras(bundle);
            //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(i);

        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.e(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
            Log.e(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }


    private void updateLoginDate(final Context context) {
        if (sp.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            if (userid.length() > 1 && !userid.substring(0, 1).equals("-")) {
                String path = URLConstants.更新用户最后登录时间 + userid + "&userOpenId=1&version=" + getVersion(context) + "&phoneType="
                        + android.os.Build.MANUFACTURER + "-" + android.os.Build.MODEL.replace(" ", "");
                StringRequest request = new StringRequest(Request.Method.GET, path,
                        new Response.Listener<String>() {

                            @Override
                            public void onResponse(String s) {
                                if (!TextUtils.isEmpty(s)) {
                                    try {
                                        Gson gson = new Gson();
                                        SuccessOrFailBean bean = gson.fromJson(s, SuccessOrFailBean.class);
                                        if (bean.status == 0) {
                                            sp.putString(context, ShareFile.USERFILE, ShareFile.ENDLOGINDATE, DateUtil.formatDate(new Date()));
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {

                    }
                });
                request.setTag("down");
                request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
                App.getHttpQueues().add(request);
            }
        } else {
            String path = URLConstants.新游客试用 + "?phoneType=" + android.os.Build.MODEL.replace(" ", "")
                    + "&id=" + userid + "&version=" + getVersion(context) + "&pushMac=" + JPushInterface.getRegistrationID(context);
            StringRequest request = new StringRequest(Request.Method.GET, path,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String result) {
                            String re = result;
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                }
            });
            request.setTag("resgin");
            request.setRetryPolicy(new DefaultRetryPolicy(3000, 1, 1.0f));
            App.getHttpQueues().add(request);
        }
    }

    public String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return "V" + version;
        } catch (Exception e) {
            e.printStackTrace();
            return "V6.3.2";
        }
    }
}
